package com.ruitaowang.admin.config;

import org.apache.catalina.webresources.StandardRoot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.web.servlet.ErrorPage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by neal on 11/15/16.
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    public static final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfig.class);
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                if (TomcatEmbeddedServletContainerFactory.class.isAssignableFrom(container.getClass())) {

                    int cacheSize = 10 * 1024 * 1024;
                    LOGGER.info("Customizing tomcat factory. New cache size (KB) is " + cacheSize);

                    TomcatEmbeddedServletContainerFactory tomcatFactory = (TomcatEmbeddedServletContainerFactory) container;
                    tomcatFactory.addContextCustomizers((context) -> {
                        StandardRoot standardRoot = new StandardRoot(context);
                        standardRoot.setCacheMaxSize(cacheSize);
                        context.setResources(standardRoot); // This is what made it work in my case.
                    });
                }
            }
        };
    }
    @Bean
    public AuthorizationInterceptor getAuthorizationInterceptor(){
        return new AuthorizationInterceptor();
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("/","classpath:/");
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .maxAge(3600)
                .allowCredentials(true);
    }
}
